import { CommentOutlined,DeleteOutlined  } from '@ant-design/icons';
import { Conversations } from '@ant-design/x';
import { message,Space,theme  } from 'antd';
import React from 'react';
import { Button } from 'antd';
import LogoNode from '../LogoNode/LogoNode';
import useStyle from '../../views/Index';
import { deleteConversation } from '../../utils/ApiRequest';
import { useEffect, useState } from 'react';


// 定义API的基础URL和路径
const BASE_URL = process.env.REACT_APP_API_BASE_URL;
const PATH = process.env.REACT_APP_API_PATH;


const groupable = {
  title: (group, { components: { GroupTitle } }) =>
    group ? (
      <GroupTitle >
        <div >
          {group}
        </div>
      </GroupTitle>
    ) : <GroupTitle />,
};


const ConversationsManger = ({ onAddConversation, onConversationClick, conversationsItems, activeKey, setConversationsItems,setActiveKey }) => {
  const [lastDeletedKey, setLastDeletedKey] = useState(null); // 用于记录最后删除的 key
  const { styles } = useStyle();

  useEffect(() => {
    if (lastDeletedKey !== null) {
      message.success('删除成功'); // 在状态更新后触发 message
      setLastDeletedKey(null); // 清空记录
    }
  }, [conversationsItems, lastDeletedKey]);

  const menuConfig = (conversation, setConversationsItems, setLastDeletedKey) => ({
    items: [
      {
        label: '删除',
        key: 'DeleteConversation',
        icon: <DeleteOutlined />,
        danger: true,
      },
    ],
    onClick: async (menuInfo) => {
      if (menuInfo.key === 'DeleteConversation') {
        try {
          const response = await deleteConversation(conversation.key);
          if (response.errcode === 200) {
            const newItems = conversationsItems.filter(item => item.key !== conversation.key);
            setConversationsItems(newItems);
            setLastDeletedKey(conversation.key); // 记录删除的 key

             if (activeKey === conversation.key) {
              onAddConversation();
            }else {
              console.log(activeKey)
              onAddConversation();
            }
          } else {
            message.error('删除失败');
          }
        } catch (error) {
          message.error(error.message || '发生未知错误');
        }
      }
    },
  });
  
  return (
    <Conversations
    // defaultActiveKey="item1"  // 默认选中项
    menu={(conversation) => menuConfig(conversation, setConversationsItems, setLastDeletedKey)}
    items={conversationsItems}
    groupable={groupable}
    className={styles.conversations}
    onActiveChange={onConversationClick}
    activeKey={activeKey}
  />
  )
};
export default ConversationsManger;